/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package co.com.smart.hawk.view.impl;

import co.com.smart.connection.model.manager.EntityManagerProvider;
import co.com.smart.connection.model.utility.Utility;
import co.com.smart.eagle.dto.EagleUsuarioDTO;
import co.com.smart.eagle.dto.GroupMenu;
import co.com.smart.eagle.dto.ResourceSecurity;
import co.com.smart.eagle.dto.ResourceSecurity.ALLOWED;
import co.com.smart.eagle.servicehandler.login.SmartEagleServiceLogin;
import co.com.smart.eagle.servicehandler.login.SmartEagleServiceLoginImpl;
import co.com.smart.hawk.controller.*;
import co.com.smart.hawk.controller.impl.*;
import co.com.smart.hawk.dto.UsuarioDTO;
import co.com.smart.hawk.utilities.HawkImageFondo;
import co.com.smart.hawk.utilities.HawkSessionMgr;
import co.com.smart.hawk.utilities.HawkViewMgr;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.beans.PropertyVetoException;
<<<<<<< HEAD
=======
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.Collections;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
>>>>>>> hawk_menu
import javax.swing.ImageIcon;
import javax.swing.JComponent;
import javax.swing.JDesktopPane;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.SwingWorker;

/**
 *
 * @author Andres
 */
public class HawkMenuImpl extends javax.swing.JFrame {
    private HawkDatosMaestrosCtrl hawkDatosMaestrosCtrl;

    /**
     * Creates new form HawkMenuImpl
     */
    public HawkMenuImpl() {

        if (HawkViewMgr.getInstance().getObjectInstance(this.getClass()) == null) {
            initComponents();
            this.setLocationRelativeTo(null);
            this.desktopMenu.setBorder(new HawkImageFondo("/img/smart-jungle-banner.png"));
            this.desktopMenu.add(this.jpmPrincipal);
            initEvent();
            initMenu();
            HawkViewMgr.getInstance().setObjectInstance(this);
        }
    }

    private void initEvent() {

        this.addWindowListener(new WindowAdapter() {

            @Override
            public void windowClosing(WindowEvent e) {
                SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() {

                    @Override
                    protected Void doInBackground() throws Exception {
                        return null;
                    }

                    @Override
                    protected void done() {
                        cancelarProceso();
                    }
                };
                worker.execute();
            }
        });

        this.desktopMenu.addMouseListener(new MouseAdapter() {

            @Override
            public void mouseClicked(MouseEvent e) {

                if (e.isPopupTrigger()) {
                    jpmPrincipal.show(HawkMenuImpl.this, e.getX(), e.getY());
                }

            }

            @Override
            public void mousePressed(MouseEvent e) {
                if (e.isPopupTrigger()) {
                    jpmPrincipal.show(HawkMenuImpl.this, e.getX(), e.getY());
                }
            }

            @Override
            public void mouseReleased(MouseEvent e) {
                if (e.isPopupTrigger()) {
                    jpmPrincipal.show(HawkMenuImpl.this, e.getX(), e.getY());
                }
            }
        });
    }

    private void cancelarProceso() {
        int message = JOptionPane.showConfirmDialog(this, "Está seguro que desea salir?", "Salir", JOptionPane.YES_NO_OPTION);
        if (message == JOptionPane.YES_OPTION) {
            EntityManagerProvider.getProvider("").closeResources();
            HawkViewMgr.getInstance().removeObjectInstance(this.getClass());
            HawkSessionMgr.getInstance().removeSession();
            System.gc();
            this.dispose();
            System.exit(0);
        }
    }

    /**
     * Inicializa el menu de Smart Hawk utilizando servicios de Smart Eagle
     */
    private void initMenu(){
        SmartEagleServiceLogin loginSmartEagle = new SmartEagleServiceLoginImpl();
        EagleUsuarioDTO user = new EagleUsuarioDTO();
        UsuarioDTO userSession = (UsuarioDTO) HawkSessionMgr.getInstance().getSession("USER_SESSION");
        user.setNombreUsuario(userSession.getDsusuario());
        user.setApp("Smart Hawk");
        List<GroupMenu> listMenus = loginSmartEagle.getMenu(user);
        setJMenuBar(jmbPrincipal);
        JMenu menu = new JMenu();
        generateMenu(listMenus, jmbPrincipal, 0, menu);
    }
    
    public static int generateMenu(List<GroupMenu> grupoMenu, JMenuBar menub, int agregados, JMenu menu) {
        int valorRetorno = agregados;
        if (grupoMenu != null) {
            Collections.sort(grupoMenu);
            for (final GroupMenu grupo : grupoMenu) {
                if (grupo.getSubMenus() != null) {
                    JMenu subMenu = new JMenu(grupo.getNombre());
                    int valor = generateMenu(grupo.getSubMenus(), menub, agregados, subMenu);
                    if (valor > agregados) {
                        menub.add(subMenu);
                    }
                    valorRetorno += valor;
                } else {
                    final String view = grupo.getUri();
                    final String context = grupo.getContexto();
                    if (context != null) {
                        JMenuItem item = new JMenuItem();
                        item.addActionListener(new ActionListener() {

                            @Override
                            public void actionPerformed(ActionEvent e) {
                                try {
                                    Class clazz = Class.forName(view);
                                    Constructor constructor = clazz.getConstructor(JDesktopPane.class);
                                    Object instance = constructor.newInstance(desktopMenu);
                                    desktopMenu.add((JComponent)instance);
                                    ((Component)instance).setVisible(true);
                                } catch (InstantiationException ex) {
                                    ex.printStackTrace();
                                } catch (IllegalAccessException ex) {
                                    ex.printStackTrace();
                                } catch (IllegalArgumentException ex) {
                                    ex.printStackTrace();
                                } catch (InvocationTargetException ex) {
                                    ex.printStackTrace();
                                } catch (NoSuchMethodException ex) {
                                    ex.printStackTrace();
                                } catch (SecurityException ex) {
                                    ex.printStackTrace();
                                } catch (ClassNotFoundException ex) {
                                    ex.printStackTrace();
                                }
                            }
                            
                        });
                        item.setText(grupo.getNombre());
                        menu.add(item);
                    }
                    valorRetorno++;
                    }

            }
        }
        return valorRetorno;
    }

    public static ALLOWED validateView(String view) {
        ALLOWED resultado = ALLOWED.DENEGADO;
        try{
        List<ResourceSecurity> recursos = (List<ResourceSecurity>)HawkSessionMgr.getInstance().getSession("USER_RESOURCES");
        for (ResourceSecurity recurso : recursos) {
            if (recurso.getUri().contains(view)) {
                if (resultado != ALLOWED.PERMITIDO) {
                    resultado = recurso.getAllowed();
                }
            }
        }
        }catch(Throwable t){
            JOptionPane.showMessageDialog(null,"Error cargando los recursos del usuario:\n"+t.getMessage());
        }
        return resultado;
    }
    
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jpmPrincipal = new javax.swing.JPopupMenu();
        jmpAdministrar = new javax.swing.JMenu();
        jmipClientes = new javax.swing.JMenuItem();
        jMenuItem2 = new javax.swing.JMenuItem();
        jCheckBoxMenuItem1 = new javax.swing.JCheckBoxMenuItem();
        jMenuItem3 = new javax.swing.JMenuItem();
        jMenu1 = new javax.swing.JMenu();
        jMenuItem5 = new javax.swing.JMenuItem();
        desktopMenu = new javax.swing.JDesktopPane();
        jmbPrincipal = new javax.swing.JMenuBar();

        jmpAdministrar.setText("Administrar");
        jmpAdministrar.setToolTipText("Administrar");

        jmipClientes.setText("Clientes");
        jmipClientes.setToolTipText("");
        jmipClientes.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jmipClientesActionPerformed(evt);
            }
        });
        jmpAdministrar.add(jmipClientes);

        jpmPrincipal.add(jmpAdministrar);

        jMenuItem2.setText("jMenuItem2");

        jCheckBoxMenuItem1.setSelected(true);
        jCheckBoxMenuItem1.setText("jCheckBoxMenuItem1");

        jMenuItem3.setText("jMenuItem3");

        jMenu1.setText("jMenu1");

        setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
        setTitle(":.SmartHawk.:");
        setIconImage(new ImageIcon(getClass().getResource("/img/smart-jungle.png")).getImage());
        setJMenuBar(jmbPrincipal);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(desktopMenu, javax.swing.GroupLayout.DEFAULT_SIZE, 1275, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(desktopMenu, javax.swing.GroupLayout.DEFAULT_SIZE, 593, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jmipClientesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jmipClientesActionPerformed
        // TODO add your handling code here:
        eventsAdministrarClientes();
    }//GEN-LAST:event_jmipClientesActionPerformed

    /**
     * Evento opcion crear Clientes
     */
    private void eventsAdministrarClientes(){
        
        HawkClientesCtrl hawkClientesCtrl = new HawkClientesCtrlImpl(Utility.initManager("SmartHawkPU"));
        HawkClientesViewImpl hawkClientesViewImpl = new HawkClientesViewImpl(this.desktopMenu,hawkClientesCtrl);
        this.desktopMenu.add(hawkClientesViewImpl);
        hawkClientesViewImpl.setVisible(true);
        hawkClientesViewImpl.pack();
        
    }
    
    /**
     * 
     */
    private void eventsArticulos(){
        
        HawkArticulosCtrl  hawkArticulosCtrl = new HawkArticulosCtrlImpl(Utility.initManager("SmartHawkPU"));
        HawkArticulosViewImpl hawkArticulosView = new HawkArticulosViewImpl(this.desktopMenu,hawkArticulosCtrl);
        this.desktopMenu.add(hawkArticulosView);
        hawkArticulosView.setVisible(true);
        hawkArticulosView.pack();
        
        
    }
    
    private void eventsEmpresas(){
<<<<<<< HEAD
        HawkEmpresasCtrl hawkEmpresasCtrl = new HawkEmpresasCtrlImpl(Utility.initManager());
        HawkEmpresasViewImpl hawkEmpresasViewImpl = new HawkEmpresasViewImpl(this.desktopMenu, hawkEmpresasCtrl);
=======
        HawkEmpresasCtrl hawkEmpresasCtrl = new HawkEmpresasCtrlImpl(Utility.initManager("SmartHawkPU"));
        HawkDatosMaestrosCtrl hawkDatosMaestrosCtrl = new HawkDatosMaestrosCtrlImpl(Utility.initManager("SmartHawkPU"));
        HawkDepartamentosCtrl hawkDepartamentosCtrl = new HawkDepartamentosCtrlImpl(Utility.initManager("SmartHawkPU"));
        HawkCiudadesCtrl hawkCiudadesCtrl = new HawkCiudadesCtrlImpl(Utility.initManager("SmartHawkPU"));
        HawkTercerosCtrl hawkTercerosCtrl = new HawkTercerosCtrlImpl(Utility.initManager("SmartHawkPU"));
        HawkEmpresasViewImpl hawkEmpresasViewImpl = new HawkEmpresasViewImpl(this.desktopMenu, hawkEmpresasCtrl, hawkDatosMaestrosCtrl, hawkDepartamentosCtrl, hawkCiudadesCtrl, hawkTercerosCtrl);
>>>>>>> hawk_menu
        this.desktopMenu.add(hawkEmpresasViewImpl);
        hawkEmpresasViewImpl.setVisible(true);
        hawkEmpresasViewImpl.pack();
    }
    
     /** 
     * 
     */
    private void eventsClienteProveedor(){
        
        HawkTercerosCtrl  hawkTercerosCtrl = new HawkTercerosCtrlImpl(Utility.initManager("SmartHawkPU"));
        HawkDatosMaestrosCtrl hawkDatosMaestrosCtrl= new HawkDatosMaestrosCtrlImpl(Utility.initManager("SmartHawkPU"));
        HawkDepartamentosCtrl hawkDepartamentosCtrl= new HawkDepartamentosCtrlImpl(Utility.initManager("SmartHawkPU"));
        HawkCiudadesCtrl hawkCiudadesCtrl=new HawkCiudadesCtrlImpl(Utility.initManager("SmartHawkPU"));
        HawkClienteProveedorViewImpl hawkClienteProveedorView = new HawkClienteProveedorViewImpl(this.desktopMenu,hawkTercerosCtrl,hawkDatosMaestrosCtrl,hawkDepartamentosCtrl,hawkCiudadesCtrl);
        this.desktopMenu.add(hawkClienteProveedorView);
        hawkClienteProveedorView.setVisible(true);
        hawkClienteProveedorView.pack();
        
        
    }
    
     /** 
     * 
     */
    private void eventsSitios(){
        
        HawkSitiosCtrl  hawkSitiosCtrl = new HawkSitiosCtrlImpl(Utility.initManager("SmartHawkPU"));
        HawkSitiosViewImpl hawkSitiosView = new HawkSitiosViewImpl(this.desktopMenu,hawkSitiosCtrl);
        this.desktopMenu.add(hawkSitiosView);
        hawkSitiosView.setVisible(true);
        try {
            hawkSitiosView.setSelected(true);
        } catch (PropertyVetoException ex) {
           JOptionPane.showMessageDialog(desktopMenu,"Error carga inicial","Error",JOptionPane.ERROR_MESSAGE);
        }
        
        
    }
     /** 
     * 
     */
    private void eventsInventarioInicial(){
        
        HawkInventarioInicialCtrl  hawkInventarioInicialCtrl = new HawkInventarioInicialCtrlImpl(Utility.initManager("SmartHawkPU"));
        HawkInventarioInicialViewImpl hawkInventarioInicialView = new HawkInventarioInicialViewImpl(this.desktopMenu,hawkInventarioInicialCtrl);
        this.desktopMenu.add(hawkInventarioInicialView);
        hawkInventarioInicialView.setVisible(true);
        try {
            hawkInventarioInicialView.setSelected(true);
        } catch (PropertyVetoException ex) {
           JOptionPane.showMessageDialog(desktopMenu,"Error carga inicial","Error",JOptionPane.ERROR_MESSAGE);
        }
        
    }
    
    public JDesktopPane getDesktop() {
        return this.desktopMenu;
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private static javax.swing.JDesktopPane desktopMenu;
    private javax.swing.JCheckBoxMenuItem jCheckBoxMenuItem1;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenuItem jMenuItem2;
    private javax.swing.JMenuItem jMenuItem3;
    private javax.swing.JMenuItem jMenuItem5;
    private javax.swing.JMenuBar jmbPrincipal;
    private javax.swing.JMenuItem jmipClientes;
    private javax.swing.JMenu jmpAdministrar;
    private javax.swing.JPopupMenu jpmPrincipal;
    // End of variables declaration//GEN-END:variables
}
